package com.capgemini.diabeo.manager;

import java.util.ArrayList;
import java.util.List;

import com.capgemini.diabeo.model.Category;
import com.capgemini.diabeo.model.Dish;
import com.capgemini.diabeo.model.Menu;
import com.capgemini.diabeo.model.MenuDish;
import com.capgemini.diabeo.service.DishService;
import com.capgemini.diabeo.service.MenuDishService;
import com.capgemini.diabeo.service.MenuService;
import com.googlecode.androidannotations.annotations.AfterInject;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.api.Scope;

@EBean(scope = Scope.Singleton)
public class DishManager {

	private Menu currentMenu;

	@Bean
	DishService dishService;

	@Bean
	MenuService menuService;

	@Bean
	MenuDishService menuDishService;

	private Category selectedCategory;

	@AfterInject
	public void afterInject() {
	}

	public void setCategory(Category category) {
		this.selectedCategory = category;
	}

	public synchronized void createNewMenu() {
		MealStatus dishStatus = MealStatus.get(currentMenu.getMealTime());
		currentMenu.setStatus(MenuStatus.HOLD.getValue());
		menuService.update(currentMenu);
		currentMenu = menuService.createNewMenu(dishStatus);
	}

	public synchronized void setMenuMeal(MealStatus mealEnum) {
		currentMenu = menuService.retrieveCurrentMenu(mealEnum);
		if (currentMenu == null) {
			currentMenu = menuService.createNewMenu(mealEnum);
		} else {
			currentMenu.calculateTotals();
		}
	}

	public List<Dish> retrieveDishByMenuStatus() {
		return dishService.retrieveDishList(selectedCategory);
	}
	
	public List<Dish> retrieveHistoryDish(Menu menu){
		return dishService.getHistoriqueDishs(menu);
	}
	
	public List<Menu> retrieveHistoryMenu(){
		return menuService.retrieveHistoryMenu();
	}

	public MealStatus getConvertedDishStatus() {
		MealStatus dishStatus = MealStatus.get(currentMenu.getMealTime());
		return dishStatus.convert();
	}

	public Menu getCurrentMenu() {
		return currentMenu;
	}

	public void addDishToMenu(Dish dish) {
		MenuDish menuDish = menuDishService
				.createNewMenuDish(currentMenu, dish);
		currentMenu.addMenuDish(menuDish);
		menuService.update(currentMenu);

	}

	public void removeDishToMenu(Dish dish) {
		MenuDish menuDish = currentMenu.removeDish(dish);
		menuDishService.delete(menuDish);
		menuService.update(currentMenu);
	}

	public void setCurrentMenu(Menu menu) {
		currentMenu = menu;
	}

	public List<Dish> getMenuDishes() {
		List<MenuDish> menuDishList = currentMenu.getMenuDishList();
		List<Dish> dishList = new ArrayList<Dish>();
		for (MenuDish menuDish : menuDishList) {
			dishList.add(menuDish.getDish());
		}
		return dishList;
	}
}
